import axios, { AxiosError } from 'axios'

const request = axios.create({
    timeout: 60000 // 请求超时时间
})

const token = {
    access_token: '',
    refresh_token: '',
    created_at: 0
};

async function authenticate(username: string, password: string) {
    const formData = new FormData();
    formData.append('grant_type', 'password');
    formData.append('username', username);
    formData.append('password', password);
    formData.append('scope', 'api');
    const rs = await axios.post('/oauth/token', formData);
    if (rs.data?.access_token) {
        token.access_token = rs.data.access_token;
        token.refresh_token = rs.data.refresh_token;
        token.created_at = rs.data.created_at;
    }
}
async function refreshToken() {
    const formData = new FormData();
    formData.append('grant_type', 'refresh_token');
    formData.append('refresh_token', token.refresh_token);
    const rs = await axios.post('/oauth/token', formData);
    if (rs.data?.access_token) {
        token.access_token = rs.data.access_token;
        token.refresh_token = rs.data.refresh_token;
        token.created_at = rs.data.created_at;
    }
}

async function checkToken(){
    if (!token.refresh_token) {
        await authenticate('guoxudong', 'Guoxd0612');
    }
    else if (Date.now() > (token.created_at + 3600) * 1000) {
        await refreshToken();
    }
}

// 创建 axios 实例

// 异常拦截处理器
const errorHandler = (error: AxiosError) => {
    if (error.response) {
        console.error(`请求返回${error.response.status}`);
    }
    return Promise.reject(error instanceof Error ? error : new Error(String(error)))
}

// request interceptor
request.interceptors.request.use(async config => {
    await checkToken();
    config.headers['Authorization'] = `Bearer ${token.access_token}`
    return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
    return response
}, errorHandler)


export default request

